const got = require('got');
const GenerateSign = require('./generateSign');
/**
 * 字符串工具函数
 * 从 'xxx=yyy' 中提取 'yyy'
 *
 * @param {*} key
 * @return {string} value
 */
const transformKey = (key) => {
    return key.substring(key.indexOf('=') + 1, key.indexOf(';'));
};

/**
 * 随机字符串
 *
 * @param {number} [length=6]
 * @return {*}
 */
const ramdomString = (length = 6) => {
    let str = 'abcdefghijklmnopqrstuvwxyz';
    str += str.toUpperCase();
    str += '0123456789';
    let _str = '';
    for (let i = 0; i < length; i++) {
        let rand = Math.floor(Math.random() * str.length);
        _str += str[rand];
    }
    return _str;
};

async function getCookies(wsKeyCk) {
    let tokenKey = await get_tokenKey('100012043978', ramdomString(40), wsKeyCk);
    if (tokenKey) {
        let url = `https://un.m.jd.com/cgi-bin/app/appjmp?to=https%3A%2F%2Fh5.m.jd.com%2FbabelDiy%2FZeus%2F3GLKTyWnMBER5M6vx6wAw663Jbfz%2Findex.html&tokenKey=${tokenKey}&lbs=`;
        const response = await got.get(url, {
            headers: {
                Connection: 'Keep-Alive',
                'Content-Type': 'application/x-www-form-urlencoded; Charset=UTF-8',
                Cookie: wsKeyCk,
                'User-Agent': require('../USER_AGENTS.js').USER_AGENT,
            },
            // 是否遵循重定向响应 默认(true)
            followRedirect: false
        });
        const pt_key = transformKey(response.headers['set-cookie'][2]);
        const pt_pin = transformKey(response.headers['set-cookie'][3]);
        if (pt_key.indexOf("fake_") >= 0 || pt_pin.indexOf("%2A%2A%2A%2A%2A%2A") >= 0) {
            return '';
        }
        return `pt_key=${pt_key};pt_pin=${pt_pin};`;
    }
    return '';
}

async function get_tokenKey(skuid, uuid, wsKeyCk) {
    let bodyString = `{"action": "to", "to": "https%3A%2F%2Fdivide.jd.com%2Fuser_routing%3FskuId%3D${skuid}"}`;
    let functionId = 'genToken';
    let sign = await get_sign(functionId, bodyString, uuid);
    if (sign) {
        const resp = await get_info(functionId, uuid, sign, bodyString, wsKeyCk);
        return resp['tokenKey'];
    }
    return '';
}

async function get_sign(functionId, body_string, uuid) {
    let data = {
        body: body_string,
        functionId: functionId,
        clientVersion: '9.2.0',
        client: 'android',
        uuid: uuid
    };
    let resp = await getSignFromJniSim(data);
    return `st=${resp['st']}&sign=${resp['sign']}&sv=${resp['sv']}`;
}

async function getSignFromJniSim(data) {
    const {functionId, clientVersion, uuid, client, body} = data;
    const timeStamp = new Date().getTime();
    const sign = await GenerateSign.getSign(functionId, body, uuid, client, clientVersion, timeStamp);
    return {sv: '111', st: timeStamp, sign: sign};
}

async function get_info(functionId, uuid, sign, body_string, wsKeyCk) {
    let url = `https://api.m.jd.com/client.action?functionId=${functionId}&clientVersion=9.2.0&client=android&uuid=${uuid}&${sign}`;
    const res = await got.post(url, {
        responseType: 'json',
        form: {
            body: body_string,
        },
        headers: {
            Cookie: wsKeyCk,
            Connection: 'Keep-Alive',
            'Content-Type': 'application/x-www-form-urlencoded; Charset=UTF-8',
            Accept: 'application/json, text/plain, */*',
            'Host': 'api.m.jd.com',
            'User-Agent': require('../USER_AGENTS.js').USER_AGENT
        },
    });
    console.log(res.body)
    return res.body;
}

module.exports = {
    getCookies
};